import time

import ujson
import usocket

import wifiModule

# 连接wifi
wifiModule.connected_wifi()

num = 0


# HTTP请求处理函数
def handle_request(client_socket):
    global num
    # 读取客户端发送的HTTP请求
    request = client_socket.recv(1024)
    if request:
        # 解析请求行，获取请求方法、路径和协议版本
        request_line = request.decode('utf-8').split('\r\n')[0]
        method, path, protocol = request_line.split(' ')

        num += 1

        # 假设我们只处理GET请求，并且路径为'/'
        if method == 'GET' and path == '/':
            # 准备JSON数据
            data = {
                'message': 'Hello, World!',
                'num': num,
                'timestamp': int(time.time())
            }

            # 将JSON数据编码为字节串
            json_response = ujson.dumps(data)

            # 创建HTTP响应头部
            response_headers = b'HTTP/1.1 200 OK\r\n'
            response_headers += b'Content-Type: application/json\r\n'
            response_headers += b'Content-Length: {}\r\n'.format(len(json_response))
            response_headers += b'\r\n'

            # 发送响应头部和JSON数据
            client_socket.sendall(response_headers + json_response)

            # 关闭连接
            client_socket.close()
        else:
            # 对于其他请求，发送404响应
            not_found_response = b'HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\nNot Found'
            client_socket.sendall(not_found_response)
            client_socket.close()
    else:
        # 如果请求为空，则关闭连接
        client_socket.close()

    # 创建一个socket对象并绑定到80端口


s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
s.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
s.bind(('', 80))
s.listen(5)

while True:
    client, addr = s.accept()
    print('访问来自:\t', addr)
    handle_request(client)
